package middleware

import (
	"fx_swift_ifcgate_agent/pkg/code"
	"fx_swift_ifcgate_agent/pkg/global"
	"fx_swift_ifcgate_agent/pkg/jwt"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/v2/container/gvar"
	"github.com/gogf/gf/v2/frame/g"
	"net/http"
	"strings"
)

func CheckAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取token
		tokenContent := c.Request.Header.Get("Authorization")
		headerPrefix := "fx"
		if tokenContent == "" {
			code.Fail(c, http.StatusUnauthorized, code.ErrInvalidAuthHeader, "header must have authorization")
			c.Abort()
			return
		}
		tokenArr := strings.Split(tokenContent, " ")
		if len(tokenArr) < 2 {
			code.Fail(c, http.StatusUnauthorized, code.ErrInvalidAuthHeader, "authorization header format must be imden {token}")
			c.Abort()
			return
		}
		if tokenArr[0] != headerPrefix {
			code.Fail(c, http.StatusUnauthorized, code.ErrInvalidAuthHeader, "authorization header format must be imden {token}")
			c.Abort()
			return
		}

		// 解析token
		userClaims, err := jwt.Parse(tokenArr[1])
		if err != nil {
			code.Fail(c, http.StatusUnauthorized, code.ErrInvalidAuthHeader, err.Error())
			c.Abort()
			return
		}

		// 判断token是否失效
		redisResult := &gvar.Var{}
		redisResult, err = g.Redis().Get(c, userClaims.Account)
		if err != nil {
			code.Fail(c, http.StatusNotAcceptable, code.ErrBind, "该帐号存在异常")
			c.Abort()
			return
		}
		if redisResult.Val() == nil {
			code.Fail(c, http.StatusNotAcceptable, code.ErrBind, "该帐号存在异常")
			c.Abort()
			return
		}
		if global.ViperObj.GetBool("sign_in.flag") {
			if redisResult.Val() != tokenArr[1] {
				code.Fail(c, http.StatusNotAcceptable, code.ErrBind, "该帐号存在异常")
				c.Abort()
				return
			}
		}

		// 将Token信息存入上下文
		c.Set("Account", userClaims.Account)
		c.Set("Email", userClaims.Email)
		c.Set("UserType", "agent")

		c.Next()
	}
}
